<template>
	<view class="publish">
		<view class="bannerImg">
			<image :src="url+tfimg" mode="" @click="toWyfb"></image>
		</view>
		<view class="main_body">
			<ul>
				<li v-for="item in list">
					<view class="ggBox">
						<view class="ggTitle">{{item.ggName}}</view>
						<view class="ggZt" v-if="item.state==0&&item.isZf==0">未审核</view>
						<view class="ggZt" v-if="item.state==1&&item.isZf==0">
							<button @click="open(item)" class="qtf">去投放</button>
						</view>
						<view class="ggZt" v-if="item.state==2">未通过</view>
						<view class="ggZt" v-if="item.state==1&&item.isZf==1" style="color: #6a8473;">正在投放</view>
						<view class="ggZt" v-if="item.state==1&&item.isZf==3" style="color: red;">投放结束</view>
					</view>
					<view class="ggTime">{{item.createtime}}</view>
				</li>
			</ul>
		</view>
		<!-- 投放弹窗 -->
		<uni-popup ref="popup" type="bottom" border-radius="10px 10px 0 0">
			<view class="popup">
				<!-- 关闭窗口 -->
				<view class="gb">
					<image src="../../static/img/colse.png" mode="" class="colse" @click="colse"></image>
				</view>
				<!-- 投放信息 -->
				<view class="tfInfo">
					<view class="ggName">
						{{info.ggName}}
					</view>
				</view>
				<view class="main_body">
					<view class="character">
						<view class="leftTit">投放开始日期： </view>
						<view class="picker-container">
						  <picker mode="date" :value="obj.startTime" @change="onStartDateChange">
							<view class="uni-input">{{ obj.startTime }}</view>
						  </picker>
						</view>
					</view>
					<view class="character">
						<view class="leftTit">投放结束日期：</view>
						<input v-model="obj.endTime" disabled  style="font-size: 26rpx;margin-top: -1rpx;color: #808080;" type="text" placeholder="请选择投放结束日期">
					</view>
					<view class="character">
						<view class="leftTit">投放天数： </view>
						<uni-number-box v-model="obj.day" style="margin-top: -5rpx;color: #808080;" :min="1" :max="31" @change="getFiveDaysAfter(obj.startTime)"/>
					</view>
				</view>
				<view class="privacyBox">
					<view class="notice" @click="HandleNotice(0)">《关于广告价格的说明》</view>
					<view class="payNotice" @click="HandleNotice(1)">《关于支付的相关说明》</view>
				</view>
				<view class="privacyBottom">
					<view v-if="price" class="privacyPrice">￥{{price}}</view>
					<button class="tfBtn" @click="HandleTf(info)">立即投放</button>
				</view>
			</view>
		</uni-popup>
		<!-- 广告价格协议弹窗 -->
		<uni-popup ref="popupXy" type="bottom" border-radius="10px 10px 0 0">
			<view class="popup">
				<!-- 关闭窗口 -->
				<view class="gb">
					<image src="../../static/img/colse.png" mode="" class="colse" @click="colseXy"></image>
				</view>
				<view class="contentXy">
					{{szInfo.content}}
				</view>
			</view>
		</uni-popup>
		<view class="wyfb">
			<image src="../../static/img/img/jia2.png" @click="toWyfb"></image>
		</view>
	</view>
</template>

<script>
	import btnlogin from '@/components/butlogin';
	import { getputInList,userInfo,getputInSz,getgg,getzf,putInXg,putInJs} from '@/api/api.js'
	import { getPay,getEnrollTran } from '@/api/pay.js'
	import config from '@/config'
	export default {
		data() {
			return {
				url:config.baseUrl,
				list:[],
				info:{},
				obj: {
					endTime:"",
					startTime:"请选择投放开始日期",
					day:1
				},
				token:"",
				userInfo:{},
				openid:"",
				card:"",
				szInfo:{},
				price:"",
				user:{},
				countdown:"",
				tfimg:"/uploads/web/tfimg.png"
			}
		},
		onLoad() {
			this.getUser()
		},
		methods: {
			// 获取投放列表
			getList(){
				let that = this
				let data = {
					phone : that.user.phone
				}
				getputInList(data).then((res) => {
					this.list = res.data
				  })
			},
			
			// 获取缓存并查询用户信息
			getUser(){
				let that = this
				uni.getStorage({
				    key: 'data1',
				    success: function (res) {
						that.openid = res.data.openid
						// 查询用户信息表中是否有该手机号
						userInfo(res.data.phone).then((userRes) => {
							that.user = userRes.info
							that.card = userRes.info.card
							that.getList()
						  })
				    }
				});
			},
			
			// 获取价格
			getPrice(){
				getputInSz().then((res) => {
					this.szInfo = res.data[0]
				  })
			},
			
			// 计算价格
			calPrice(){
				this.price = this.obj.day*this.szInfo.price
			},
			
			// 价格说明
			HandleNotice(item){
				this.$refs.popupXy.open('bottom')
				if(item==0){
					this.getPrice()
				}else if(item==1){
					getzf().then((res) => {
						this.szInfo = res.data[0]
					  })
				}
			},
			
			// 支付相关说明
			HandlePay(){
				console.log('支付相关说明')
			},
			
			toWyfb(){
				uni.navigateTo({
					url: '../user/wyfb',
				});
			},
			
			// 去投放
			open(item){
				this.info = item
				this.getPrice()
				// 通过组件定义的ref调用uni-popup方法 ,如果传入参数 ，type 属性将失效 ，仅支持 ['top','left','bottom','right','center']
				this.$refs.popup.open('bottom')
			},
			
			// 关闭弹窗
			colse(){
				this.$refs.popup.close()
				this.obj.startTime = "请选择投放开始日期"
				this.obj.endTime = ""
				this.obj.day = 	1
				this.price = ""
			},
			
			//关闭价格协议的说明
			 colseXy(){
				 this.$refs.popupXy.close()
			 },
			
			// 立即投放--支付
			HandleTf(info){
				let that = this
				if(that.obj.startTime=='请选择投放开始日期'){
					uni.showToast({
						title: '请选择投放开始时间',
						icon: 'none',
					});
				}else{
					let temp = {
					  hname:that.info.ggName,
					  name:that.info.tfrName,
					  phone:that.info.tfrPhone,
					  card:that.card,
					  price : that.price,
					  openid:that.openid
					};
					// 支付订单
					getPay(temp).then((res) => {
						console.log('res',res.data)
						// 商户号
						that.paymentTrade = res.dataInfo	
						 // 调起支付接口
						 uni.requestPayment({
							provider: "wxpay",
							appid: res.data.appId, // 微信开放平台 - 应用 - AppId，注意和微信小程序、公众号 AppId 可能不一致
							timeStamp: res.data.timeStamp, // 时间戳（单位：秒）
							package: res.data.package, // 固定值
							paySign: res.data.paySign, //签名
							signType: res.data.signType, // 签名算法，这里用的 MD5/RSA 签名
							nonceStr: res.data.nonceStr, // 随机字符串
							success(res) {
								if (res.errMsg == "requestPayment:ok") {
									uni.showToast({
											title: '支付成功',
											icon: 'success',
										});
									// 交易记录
									let tranData = {
									  payment_type: 4,
									  payment_price:that.price,
									  payment_out_trade_no:that.paymentTrade,
									  payment_body:that.info.ggName,
									  payment_id: that.info.id,
									  payment_name:that.user.userName,
									  payment_phone : that.user.phone,
									};
									getEnrollTran(tranData).then((res) => {
										if(res.code==200){
											// 存到交易记录里面后修改投放列表的值
											let xgdata = {
												id:info.id,
												startTime:that.obj.startTime,
												endTime:that.obj.endTime,
												isZf:1,
											}
											putInXg(xgdata).then((res) => {
												console.log('resresres',res)
												if(res.code==200){
													uni.showToast({
														title: '投放成功',
														icon: 'success',
													});
													// 投放成功后开始倒计时
													// that.tartCountdown()
													uni.navigateTo({
														url: '/pages/index/index'
													});
												}else if(res.code==201){
													uni.showToast({
														title: '投放失败',
														icon: 'error',
													});
												}
											  })
										}
									 })
								}
							},
							fail(e) {
								if (e.errMsg == "requestPayment:fail cancel") {
									uni.showToast({
											title: '取消支付',
											icon: 'none',
										});
								} else {
									uni.showToast({
											title: '取消失败',
											icon: 'error',
										});
										}
									}
								})
					 })
				}
			},
			
			// 开始时间
			onStartDateChange(e) {
			      this.obj.startTime = e.target.value;
				  // 计算多少天后的日期的方法
				  this.getFiveDaysAfter(this.obj.startTime)
			    },
			// 计算多少天后的日期
			getFiveDaysAfter(dateStr) {
				if(dateStr=='请选择投放开始日期'){
					uni.showToast({
							title: "请选择开始时间",
							icon: 'none',
						});
					}else
					{
						const date = new Date(dateStr);
						date.setDate(date.getDate() + this.obj.day);
						this.obj.endTime = date.toISOString().split('T')[0]; // 返回yyyy-MM-dd格式
						// 计算具体需要支付的价格
						this.calPrice()
					}
			    },
				
			// 倒计时
			tartCountdown() {
				for (let i = 0; i < this.list.length; i++) {
					let target = new Date(this.list[i].endTime).getTime();
					let now = new Date().getTime();
					let distance = target - now;
					this.list[i].distance = distance
					if (this.list[i].distance < 0) {
					  clearInterval(this.list[i].intervalId);
					  let xgdata = {
					  	id:this.list[i].id,
					  	isZf:3,
					  }
					  putInJs(xgdata).then((res) => {
					    })
					  return;
					}
								 
					this.list[i].intervalId = this.formatCountdown(this.list[i].distance);
					this.list[i].intervalId = setInterval(() => {
					this.list[i].distance = target - new Date().getTime();
					  if (this.list[i].distance < 0) {
					    clearInterval(this.list[i].intervalId);
						// 如果时间相减小于0，传入后台改变isZf的值为3（投放结束）
						let xgdata = {
							id:this.list[i].id,
							isZf:3,
						}
						putInJs(xgdata).then((res) => {
						  })
					  } else {
					    this.list[i].countdown = this.formatCountdown(this.list[i].distance);
					  }
					}, 1000);
					console.log('list1212',this.list)
				} 
			    },
				formatCountdown(distance) {
				      // 获取时间单位
				      let days = Math.floor(distance / (1000 * 60 * 60 * 24));
				      let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
				      let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
				      let seconds = Math.floor((distance % (1000 * 60)) / 1000);
				 
				      return days + "天 " + hours + "小时 " + minutes + "分钟 " + seconds + "秒";
				    },
		}
	}
</script>

<style>
	
	.publish,.main_body{
		width: 100%;
	}
	.main_body ul li{
		// border: 1px solid red;
		padding: 20rpx;
		/* border-radius: 10rpx; */
		margin: 10rpx auto;
		width: 91%;
		font-size: 26rpx;
		border: 1px solid #6a8473;
	}
	
	.ggBox{
		display: flex;
	}
	
	.ggZt{
		margin-left: auto;
		position: relative;
		top:18rpx;
		font-size: 26rpx;
		color: #999;
	}
	
	.ggTime{
		margin-top: 10rpx;
		font-size: 24rpx;
		font-weight: 300;
	}
	
	.ggTitle{
		color: #6a8473;
	}
	
	.wyfb{
		width: 130rpx;
		height: 130rpx;
		position: absolute;
		right:0;
		bottom: 300rpx;
	}
	
	.wyfb image{
		width: 100%;
		height:100%;
	}
	
	.colse{
		width: 40rpx;
		height: 40rpx;
		float: right;
	}
	
	.popup{
		background: #fff;
		height: 560rpx;
		width: 94.5%;
		padding: 20rpx;
	}
	
	.vue-ref{
		padding-bottom: 0!important;
	}
	
	.character{
		display: flex;
		border-bottom: 2rpx solid #e8e8e8;
		padding: 22rpx 0;
		font-size: 26rpx;
	}
	
	.uni-input {
	  width: 100%;
	  color: #808080;
	}
	
	.main_body{
		margin-top: 20rpx;
	}
	
	.tfBtn{
		margin-top: 30rpx;
		background: #6a8473;
		color: #fff;
		font-size: 26rpx;
		width:165rpx;
		float: right;
		border-radius: 0;
		font-weight: 300;
	}
	
	.qtf{
		/* border: 1px solid #6a8473; */
		font-size: 24rpx;
		background: #6a8473;
		height: 55rpx;
		line-height: 55rpx;
		color: #fff;
	}
	
	.privacyBox{
		margin-top: 20rpx;
		font-size: 22rpx;
		color: #6a8473;
		text-align: center;
	}
	
	.payNotice{
		margin-top: 15rpx;
	}
	
	.contentXy{
		margin-top: 47rpx;
		font-size: 24rpx;
		line-height: 45rpx;
		text-indent: 2em;
	}
	
	.privacyPrice{
		margin-top:44rpx;
		color: #6a8473;
		font-weight: bold;
		font-size: 38rpx;
		float: left;
		float: left;
	}
	
	.privacyBottom{
		display: inline-block;
		width: 100%;
	}
	
	.bannerImg{
		width: 100%;
		height: 540rpx;
	}
	
	.bannerImg image{
		width: 100%;
		height: 100%;
	}
	
	.leftTit,.ggName{
		color: #6a8473;
	}
	
	.uni-numbox-btns {
		border: 1px solid #6a8473;
	}
	
	.uni-numbox--text {
		color: #6a8473!important;
	}
	
	
	.uni-numbox__value {
		border: 1px solid #6a8473!important;
		color: #6a8473!important;
	}
</style>